package com.qian.ddj.web.controller;

import com.qian.api.ddj.model.OperatorLog;
import com.qian.api.ddj.model.Order;
import com.qian.api.ddj.model.OrderQueryModel;
import com.qian.api.ddj.model.StatusDict;
import com.qian.api.ddj.service.IOperatorLogService;
import com.qian.api.ddj.service.IOrderService;
import com.yaowk.api.common.BaseException;
import com.yaowk.api.common.PageReq;
import com.yaowk.api.common.PageResp;
import com.yaowk.web.common.utils.HttpUtils;
import com.yaowk.web.system.security.SecurityUtils;
import com.yaowk.web.system.security.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ddj/order")
@Api(tags = "订单管理")
@Slf4j
public class OrderController {

//    @Value("${filePath}")
//    private String filePath;

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOperatorLogService operatorLogService;

    @GetMapping
    @ApiOperation("查询用户订单")
    public PageResp<Order> list(OrderQueryModel order, PageReq pageReq) {
        order.setUserId(SecurityUtils.getUserId());
        PageResp<Order> page = orderService.findAll(order, pageReq);
        return page;
    }

    @GetMapping("export")
    @ApiOperation("导出用户订单")
    public void list(OrderQueryModel order, HttpServletResponse response) {
        if (order.getBeginTime() == null) {
            throw new BaseException("开始时间不能为空");
        }
        long time = 3 * 24 * 60 * 60 * 1000;
        if (new Date().getTime() - order.getBeginTime().getTime() > time && order.getEndTime().getTime() - order.getBeginTime().getTime() > time) {
            throw new BaseException("时间不能超过3天");
        }
        order.setUserId(SecurityUtils.getUserId());
        PageReq pageReq = new PageReq();
        pageReq.setPageSize(Integer.MAX_VALUE);
        PageResp<Order> pageResp = orderService.findAll(order, pageReq);

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell0 = row.createCell(0);
        XSSFCell cell1 = row.createCell(1);
        XSSFCell cell2 = row.createCell(2);
        XSSFCell cell3 = row.createCell(3);
        XSSFCell cell4 = row.createCell(4);
        XSSFCell cell5 = row.createCell(5);
        XSSFCell cell6 = row.createCell(6);
        XSSFCell cell7 = row.createCell(7);
        XSSFCell cell8 = row.createCell(8);
        XSSFCell cell9 = row.createCell(9);
        cell0.setCellValue("用户名");
        cell1.setCellValue("商户名");
        cell2.setCellValue("备注");
        cell3.setCellValue("下单时间");
        cell4.setCellValue("支付时间");
        cell5.setCellValue("金额");
        cell6.setCellValue("平台订单号");
        cell7.setCellValue("用户订单号");
        cell8.setCellValue("支付类型");
        cell9.setCellValue("状态");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Order> orders = pageResp.getList();
        int i = 1;
        for (Order o : orders) {
            row = sheet.createRow(i);
            cell0 = row.createCell(0);
            cell1 = row.createCell(1);
            cell2 = row.createCell(2);
            cell3 = row.createCell(3);
            cell4 = row.createCell(4);
            cell5 = row.createCell(5);
            cell6 = row.createCell(6);
            cell7 = row.createCell(7);
            cell8 = row.createCell(8);
            cell9 = row.createCell(9);
            cell0.setCellValue(o.getUsername());
            cell1.setCellValue(o.getBusinessName());
            cell2.setCellValue(o.getBody());
            if (ObjectUtils.allNotNull(o.getCreateTime())) {
                cell3.setCellValue(dateFormat.format(o.getCreateTime()));
            }
            if (ObjectUtils.allNotNull(o.getPayTime())) {
                cell4.setCellValue(dateFormat.format(o.getPayTime()));
            }
            cell5.setCellValue(o.getAmount().toString());
            cell6.setCellValue(o.getOrderNo());
            cell7.setCellValue(o.getOutOrderNo());
            if (ObjectUtils.allNotNull(o.getPayType())) {
                String payType = "";
                switch (o.getPayType()) {
                    case 1:
                        payType = "支付宝扫码";
                        break;
                    case 2:
                        payType = "支付宝WAP";
                        break;
                    case 3:
                        payType = "京东";
                        break;
                    case 4:
                        payType = "QQ扫码";
                        break;
                    case 5:
                        payType = "网银快捷";
                        break;
                    case 6:
                        payType = "微信";
                        break;
                    case 7:
                        payType = "微信H5";
                        break;
                    case 8:
                        payType = "QQWAP";
                        break;
                    case 9:
                        payType = "银联扫码";
                        break;
                }
                cell8.setCellValue(payType);
            }
            if (ObjectUtils.allNotNull(o.getStatus())) {
                String status = "";
                switch (o.getStatus()) {
                    case 1:
                        status = "待发起";
                        break;
                    case 3:
                        status = "待支付";
                        break;
                    case 4:
                        status = "支付成功";
                        break;
                    case 5:
                        status = "交易完成";
                        break;
                    case 6:
                        status = "已结算";
                        break;
                }
                cell9.setCellValue(status);
            }

            i++;
        }

        row = sheet.createRow(i);
        cell0 = row.createCell(0);
        cell1 = row.createCell(1);
        cell2 = row.createCell(2);
        cell3 = row.createCell(3);
        cell4 = row.createCell(4);
        cell5 = row.createCell(5);
        cell0.setCellValue("总金额");
        cell1.setCellValue("成功金额");
        cell2.setCellValue("失败金额");
        cell3.setCellValue("总单数");
        cell4.setCellValue("成功单数");
        cell5.setCellValue("失败单数");
        Map map = count(orders);
        i++;
        row = sheet.createRow(i);
        cell0 = row.createCell(0);
        cell1 = row.createCell(1);
        cell2 = row.createCell(2);
        cell3 = row.createCell(3);
        cell4 = row.createCell(4);
        cell5 = row.createCell(5);
        cell0.setCellValue(String.valueOf(map.get("totalMoeny")));
        cell1.setCellValue(String.valueOf(map.get("successMoeny")));
        cell2.setCellValue(String.valueOf(map.get("failMoeny")));
        cell3.setCellValue(String.valueOf(map.get("totalNumber")));
        cell4.setCellValue(String.valueOf(map.get("successNumber")));
        cell5.setCellValue(String.valueOf(map.get("failNumber")));

        String fileName = SecurityUtils.getUserInfo().getUsername() + "order.xls";
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @PostMapping("/notifyToUser/{id}")
    public void notify2User(@PathVariable Integer id) {
        Order order = new Order();
        order.setId(id);
        orderService.notifyToUser(order);
    }

    @PostMapping("/finish/{id}")
    public void orderFinish(@PathVariable Integer id, String upOrderNo, HttpServletRequest request) {
        Order order = new Order();
        order.setUpOrderNo(upOrderNo);
        order = orderService.findOne(order);
        if (order != null) {
            throw new BaseException("上游订单号已存在");
        }
        order = new Order();
        order.setId(id);
        order.setUpOrderNo(upOrderNo);
        orderService.orderFinish(order);

        OperatorLog operatorLog = new OperatorLog();
        UserInfo userInfo = SecurityUtils.getUserInfo();
        operatorLog.setUsername(userInfo.getUsername());
        operatorLog.setUserId(userInfo.getId());
        operatorLog.setOperator("确认订单,上游订单号：" + upOrderNo);
        operatorLog.setChangeId(id);
        operatorLog.setChangeName(upOrderNo);
        operatorLog.setIp(HttpUtils.getRealIp(request));
        operatorLogService.save(operatorLog);

        orderService.notifyToUser(order);
    }

    @GetMapping("/count")
    @ApiOperation("用户订单统计")
    public Map count(OrderQueryModel orderQueryModel) {
        orderQueryModel.setUserId(SecurityUtils.getUserId());
        PageReq req = new PageReq();
        req.setPageSize(Integer.MAX_VALUE);
        PageResp<Order> all = orderService.findAll(orderQueryModel, req);
        return count(all.getList());
    }

    @GetMapping("/count/all")
    @ApiOperation("后台订单统计")
    public Map countAll(OrderQueryModel orderQueryModel) {
        PageReq req = new PageReq();
        req.setPageSize(Integer.MAX_VALUE);
        PageResp<Order> all = orderService.findAll(orderQueryModel, req);
        return count(all.getList());
    }

    @GetMapping("/all")
    @ApiOperation("查询所有订单")
    public PageResp<Order> listAll(OrderQueryModel order, PageReq pageReq) {
        Long bt = System.currentTimeMillis();
        PageResp<Order> page = orderService.findAll(order, pageReq);
        log.info(" total time {}", System.currentTimeMillis() - bt);
        return page;
    }

    private Map count(List<Order> orders) {
        BigDecimal successMoney = new BigDecimal(0);
        BigDecimal failMoney = new BigDecimal(0);
        BigDecimal totalMoney = new BigDecimal(0);
        Integer successNumber = 0;
        Integer failNumber = 0;
        Integer totalNumber = 0;
        for (Order order : orders) {
            totalMoney = totalMoney.add(order.getAmount());
            totalNumber++;
            if (order.getStatus().equals(StatusDict.SUCCESS_PAY) || order.getStatus().equals(StatusDict.FINISH_PAY) || order.getStatus().equals(StatusDict.SETTLEMENT)) {
                successMoney = successMoney.add(order.getAmount());
                successNumber++;
            } else if (order.getStatus().equals(StatusDict.WAIT_PAY)) {
                failMoney = failMoney.add(order.getAmount());
                failNumber++;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("successMoeny", successMoney);
        map.put("failMoeny", failMoney);
        map.put("totalMoeny", totalMoney);
        map.put("successNumber", successNumber);
        map.put("failNumber", failNumber);
        map.put("totalNumber", totalNumber);
        return map;
    }
}
